package se.lth.student.axisandroidcam.client;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
import java.util.TreeMap;

import se.lth.axisandroidcam.client.widget.TextImageView;
import se.lth.cs.fakecamera.Axis211A;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.BitmapFactory.Options;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CameraAggregator extends BaseAdapter implements Observer {
	private Context mContext;
	private DataWrapper cam1;
	private DataWrapper cam2;

	private static final int TARGET_HEIGHT = 320;
	private static final int TARGET_WIDTH = 380;

	public CameraAggregator(Context c) {
		super();
		cam1 = null;
		cam2 = null;
		mContext = c;
	}

	public int getCount() {
		return 2;
	}

	public Object getItem(int nbr) {
		if (nbr == 0) {
			return cam1;
		} else {
			return cam2;
		}

	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		TextImageView textImageView;
		if (convertView == null) { // if it's not recycled, initialize some
			textImageView = new TextImageView(mContext);
			textImageView.setLayoutParams(new GridView.LayoutParams(TARGET_WIDTH,
					TARGET_HEIGHT));
			textImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			// imageView.setPadding(8, 8, 8, 8);
		} else {
			textImageView = (TextImageView) convertView;
			textImageView.setText("");
		}
		
		DataWrapper currentWrap = null;
		if (position == 0) {
			currentWrap = cam1;
		} else if (position == 1){
			currentWrap = cam2;
		}

		if (currentWrap != null){
			textImageView.setText("Delay: " + (System.currentTimeMillis() - Toolbox.getTimestamp(currentWrap.data)) +
					"  Movie: " + currentWrap.isMovie +
					"  Synch: " + currentWrap.isSynch);
			textImageView.setImageBitmap(BitmapFactory.decodeByteArray(currentWrap.data, 0, currentWrap.data.length));
		}
		return textImageView;
	}


	public boolean addImage(DataWrapper wrap) {
		Toolbox.printDebug("Trying to add image in imageAggr, to cam-"
				+ wrap.cameraNbr + "size: " + wrap.data.length);

		Bitmap image = BitmapFactory.decodeByteArray(wrap.data, 0, wrap.data.length);

		if (wrap.cameraNbr == 1) {
			cam1 = wrap;
		} else {
			cam2 = wrap;
		}

		CameraAggregator.this.notifyDataSetChanged();
		Toolbox.printDebug("Image is added");
		return true;
	}

	public void update(Observable observable, Object arg) {
		DataWrapper wrap = (DataWrapper) arg;
		addImage(wrap);
	}
}
